package system

import (
	"liuche17.cn/go-blog/server/global"
	"liuche17.cn/go-blog/server/model"
	"liuche17.cn/go-blog/server/model/system/resp"
	"time"
)

type DashBoardService struct{}

// GetHalfYearArticlePublishInfo 得到近半年的发布文章日期信息
func (*DashBoardService) GetHalfYearArticlePublishInfo() (map[string]int, error) {
	now := time.Now()
	halfYearAgo := now.AddDate(0, -6, 0)
	var articleList []model.Article
	err := global.GB_DB.Model(&model.Article{}).Select("id", "create_time").Where("create_time > ?", halfYearAgo).Scan(&articleList).Error
	if err != nil {
		return nil, err
	}
	// 根据日期分组
	dateGroup := groupByDate(&articleList)
	// 从半年前开始，循环到今天
	var resMap = make(map[string]int)
	for day := halfYearAgo; !day.After(now); day = day.Add(24 * time.Hour) {
		// 打印每一天的日期
		curDay := day.Format(global.DATE_FORMAT)
		resMap[curDay] = dateGroup[curDay]
	}

	return resMap, nil
}

// GetWeekArticlePV 得到周文章访问报表
func (*DashBoardService) GetWeekArticlePV() ([]resp.StatisticsArticlePV, error) {
	weekDuration := time.Now().Add(-8 * 24 * time.Hour)
	var weekDurationList []resp.StatisticsArticlePV

	// 使用数据库的日期格式化函数
	err := global.GB_DB.Model(&model.StatisticsArticlePV{}).
		Select("DATE_FORMAT(pv_date, '%Y-%m-%d') as PvDate, pv_count as PvCount").
		Where("pv_date > ?", weekDuration).
		Scan(&weekDurationList).Error

	if err != nil {
		return nil, err
	}

	return weekDurationList, nil
}

// 根据日期分组
func groupByDate(articleList *[]model.Article) map[string]int {
	var resMap = make(map[string]int)
	for _, article := range *articleList {
		publishDate := article.CreateTime.Format(global.DATE_FORMAT)
		resMap[publishDate] = resMap[publishDate] + 1
	}

	return resMap
}
